import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token'),
    user: JSON.parse(localStorage.getItem('user')) || { id: 1, username: 'admin', realName: '管理员' },
    recentArchives: [],
    notifications: []
  },
  getters: {
    isAuthenticated: state => !!state.token,
    token: state => state.token,
    user: state => state.user,
    currentUser: state => state.user,
    recentArchives: state => state.recentArchives,
    notifications: state => state.notifications
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER(state, user) {
      state.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },
    SET_RECENT_ARCHIVES(state, archives) {
      state.recentArchives = archives
    },
    SET_NOTIFICATIONS(state, notifications) {
      state.notifications = notifications
    },
    CLEAR_AUTH(state) {
      state.token = ''
      state.user = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    }
  },
  actions: {
    async login({ commit }, data) {
      // const response = await axios.post('/auth/login', credentials)
      const { token } = data
      commit('SET_TOKEN', token)
      commit('SET_USER', data)
    },
    async logout({ commit }) {
      try {
        // await axios.post('/auth/logout')
        commit('CLEAR_AUTH')
      } catch (error) {
        console.error('Logout error:', error)
        commit('CLEAR_AUTH')
      }
    },
    async fetchRecentArchives({ commit }) {
      const response = await axios.get('/archives/recent')
      commit('SET_RECENT_ARCHIVES', response.data)
      return response
    },
    async fetchNotifications({ commit }) {
      const response = await axios.get('/notifications')
      commit('SET_NOTIFICATIONS', response.data)
      return response
    }
  }
})
